/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginFrame.java
 *
 * Created on 30-dic-2011, 19:32:04
 */
package occho.view;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import javax.swing.JOptionPane;
import occho.data.LogDAO;
import occho.data.OracleDAOFactory;
import occho.data.UsuarioDAO;
import occho.model.FachadaRegistro;
import occho.model.Log;
import occho.view.resources.Messages;
import oracle.net.ns.Message11;

/**
 *
 * @author Jorge
 */
public class LoginFrame extends javax.swing.JInternalFrame implements Internacionalizable {

    private FachadaRegistro fachada = null;
    private OcchoView view = null;

    /** Creates new form LoginFrame
     * @param view 
     */
    public LoginFrame(OcchoView view) {
        initComponents();
        this.view = view;
        fachada = new FachadaRegistro();
        setLenguaje();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbUsuario = new javax.swing.JLabel();
        lbPassword = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        btnLogin = new javax.swing.JButton();
        txtPassword = new javax.swing.JPasswordField();

        setClosable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(occho.OcchoApp.class).getContext().getResourceMap(LoginFrame.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setPreferredSize(new java.awt.Dimension(365, 158));

        lbUsuario.setText(resourceMap.getString("lbUsuario.text")); // NOI18N
        lbUsuario.setName("lbUsuario"); // NOI18N

        lbPassword.setText(resourceMap.getString("lbPassword.text")); // NOI18N
        lbPassword.setName("lbPassword"); // NOI18N

        txtUsuario.setText(resourceMap.getString("txtUsuario.text")); // NOI18N
        txtUsuario.setName("txtUsuario"); // NOI18N
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyReleased(evt);
            }
        });

        btnLogin.setText(resourceMap.getString("btnLogin.text")); // NOI18N
        btnLogin.setName("btnLogin"); // NOI18N
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N
        txtPassword.setName("txtPassword"); // NOI18N
        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPasswordKeyReleased(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lbPassword)
                            .add(lbUsuario))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 53, Short.MAX_VALUE)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(txtPassword, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(txtUsuario, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, btnLogin))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lbUsuario)
                    .add(txtUsuario, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lbPassword)
                    .add(txtPassword, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(btnLogin)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
    if (validarCampos()) {
        String email = txtUsuario.getText();
        String pass = new String(txtPassword.getPassword());
        try {
            if (fachada.iniciarSesion(email, pass)) {
                view.setUsuario(fachada.getUsuario());
                
                OracleDAOFactory daoFactory = OracleDAOFactory.getInstancia();
                LogDAO lDAO = daoFactory.getLogDAO();
                Log l = new Log(view.getUsuario(),new Timestamp(Calendar.getInstance().getTimeInMillis()),"Login");
                
                if(lDAO.insertarLog(l)) view.setStatusMessageLabel("Creada entrada en log",Color.BLACK); 
                else view.setStatusMessageLabel("Error al crear entrada en log",Color.RED);                
                view.setStatusMessageLabel("Sesión iniciada como " + view.getUsuario().getEmail(), Color.BLACK);
                view.setUserApp(view.getUsuario());
                OracleDAOFactory factory = OracleDAOFactory.getInstancia();
                UsuarioDAO uDAO =factory.getUsuarioDAO();
                uDAO.setActivo(view.getUsuario().getEmail(), true);
                this.dispose();
            } else {
                //view.setStatusMessageLabel("No se pudo iniciar sesión", Color.RED);
                JOptionPane.showMessageDialog(null,"No se puedo iniciar sesión.","Error",JOptionPane.ERROR_MESSAGE);

            }
        } catch (ClassNotFoundException ex) {
            System.out.println("Class_Not_Found_Exception: " + ex.getMessage());
        } catch (SQLException ex) {
            System.out.println("SQL_Exception: " + ex.getMessage());
        }
    } else {
        //mensaje en barra de estado
        //view.setStatusMessageLabel("Error, compruebe que ha introducido todos los campos", Color.RED);
        JOptionPane.showMessageDialog(null,"Error, compruebe que ha introducido todos los campos.","Error",JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_btnLoginActionPerformed

    private void txtUsuarioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnLoginActionPerformed(null);
        }
    }//GEN-LAST:event_txtUsuarioKeyReleased

    private void txtPasswordKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnLoginActionPerformed(null);
        }
    }//GEN-LAST:event_txtPasswordKeyReleased

    private boolean validarCampos() {
        String usuario = txtUsuario.getText();
        String pass = new String(txtPassword.getPassword());
        if (usuario.isEmpty() || pass.isEmpty()) {
            return false;
        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLogin;
    private javax.swing.JLabel lbPassword;
    private javax.swing.JLabel lbUsuario;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    public void setLenguaje() {
        setTitle(Messages.getString("Form.title", Messages.BUNDLE_NAME_LOGIN));
        btnLogin.setText(Messages.getString("btnLogin.text", Messages.BUNDLE_NAME_LOGIN));
        lbPassword.setText(Messages.getString("lbPassword.text", Messages.BUNDLE_NAME_LOGIN));
        lbUsuario.setText(Messages.getString("lbUsuario.text", Messages.BUNDLE_NAME_LOGIN));
    }
}
